package com.zzz.system.controller;

import com.zzz.framework.model.AmisSource;
import com.zzz.framework.model.R;
import com.zzz.system.service.DataSourceService;
import com.zzz.system.vo.DatasourceVO;
import com.zzz.system.vo.QueryDatasourceVO;
import com.zzz.system.vo.SaveDatasourceVO;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.NotNull;

@RestController
@RequestMapping("api")
public class DatasourceController {

    @Autowired
    private DataSourceService dataSourceService;

    @PostMapping("dataSource/findByCondition")
    public R findByCondition(@RequestBody @Validated @NotNull QueryDatasourceVO queryDatasourceVO) {
        return R.data(dataSourceService.findByCondition(queryDatasourceVO));
    }

    @GetMapping("dataSource/findByCode")
    public R<DatasourceVO> findByCode(@Param("code") String code) {
        if (StringUtils.isBlank(code)) {
            return R.data(null);
        }
        return R.data(dataSourceService.findByCode(code));
    }

    @PostMapping("dataSource/testConnect")
    public R testConnect(@RequestBody @Validated @NotNull SaveDatasourceVO saveDatasourceVO) {
        return dataSourceService.testConnect(saveDatasourceVO);
    }

    @PostMapping("dataSource/add")
    public R add(@RequestBody @Validated @NotNull SaveDatasourceVO saveDatasourceVO) {
        return dataSourceService.add(saveDatasourceVO);
    }

    @PostMapping("dataSource/edit/{id}")
    public R edit(@PathVariable Long id, @RequestBody @Validated @NotNull SaveDatasourceVO saveDatasourceVO) {
        saveDatasourceVO.setId(id);
        return dataSourceService.edit(saveDatasourceVO);
    }

    @PostMapping("dataSource/remove/{id}")
    public R remove(@PathVariable Long id) {
        return dataSourceService.remove(id);
    }

    @GetMapping("dataSource/listSelect")
    public R<AmisSource> listSelect() {
        return R.data(AmisSource.of(dataSourceService.findAll(), DatasourceVO::getCode, DatasourceVO::getCode));
    }
}
